﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HelpExtension.cs" company="R.V.Kasner">
//   Copyright © 2011 R.V.Kasner
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Owen.Terminal.Commons
{
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text;
    using System.Xml.Linq;

    public static class HelpExtension
    {
        public static bool Suitability(this XName xname, string name)
        {
            return xname.ToString().ToLower() == name.ToLower();
        }

        public static byte[] ToByteArray(this int[] ints)
        {
            var bytes = new byte[ints.Length];
            for (var i = 0; i < ints.Length; i++)
            {
                bytes[i] = (byte)(ints[i] & 0xff);
            }

            return bytes;
        }

        public static int[] ToIntArray(this byte[] bytes)
        {
            var ints = new int[bytes.Length];
            for (var i = 0; i < bytes.Length; i++)
            {
                ints[i] = bytes[i];
            }

            return ints;
        }

        public static int[] ToIntArray(this string hexFormatedString)
        {
            if (string.IsNullOrWhiteSpace(hexFormatedString))
            {
                return new int[0];
            }

            var strValues = hexFormatedString.Split(' ');
            if (strValues.Length == 0)
            {
                return new int[0];
            }

            var data = new List<int>();

            foreach (var strValue in strValues)
            {
                if (string.IsNullOrWhiteSpace(strValue)) continue;
                int value;
                var result = int.TryParse(strValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value);
                if (!result)
                {
                    throw new System.FormatException("Формат значения не является hex : " + strValue);
                }

                data.Add(value);
            }

            return data.ToArray();
        }

        public static string ToStringHexFormat(this int[] bytes)
        {
            var sb = new StringBuilder();
            foreach (var b in bytes)
            {
                sb.Append(b.ToString("X2") + " ");
            }

            return sb.ToString();
        }
    }
}